package com.csun.cmny.provider.device.sleepcare;

import com.csun.cmny.provider.device.sleepcare.entity.SleepCareConstant;
import com.csun.cmny.provider.device.sleepcare.entity.SleepCareErrorCodeEnum;
import com.csun.cmny.provider.device.sleepcare.entity.param.SleepCareAllUserInfoParam;
import com.csun.cmny.provider.device.sleepcare.entity.param.SleepCareBodyMotionParam;
import com.csun.cmny.provider.device.sleepcare.entity.param.SleepCareLoginParam;
import com.csun.cmny.provider.device.sleepcare.entity.result.SleepCareAllUserInfoResult;
import com.csun.cmny.provider.device.sleepcare.entity.result.SleepCareBodyMotionResult;
import com.csun.cmny.provider.device.sleepcare.entity.result.SleepCareLoginResult;
import com.csun.cmny.provider.device.sleepcare.entity.pojo.SleepCareUserInfo;
import com.csun.cmny.provider.service.impl.HttpClientServiceImpl;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-02-22 14:16
 * @Description: the sleep care main
 */
@Slf4j
@Component
public class SleepCareProccess {

    private int loginCount = 0;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private HttpClientServiceImpl httpClientService;

    public void run() {
        loginCount = 0;
        log.info("sleep care proccess refresh data......");
        SleepCareAllUserInfoResult sleepCareAllUserInfoResult = getAllUserInfo();
        try {
            if (PublicUtil.isNotEmpty(sleepCareAllUserInfoResult)
                && PublicUtil.isNotEmpty(sleepCareAllUserInfoResult.getAllUserInfoList())) {
                for (SleepCareUserInfo userInfo : sleepCareAllUserInfoResult.getAllUserInfoList()) {
                    // 判断是否在床
                    String userId = userInfo.getUserId();   // 设备编号
                   if (userInfo.isInBed()) {
                       // 获取体动, 判断是否需要翻身
                       SleepCareBodyMotionResult sleepCareBodyMotionResult =
                               getBodyMotion(new SleepCareBodyMotionParam(userId));
                       if (PublicUtil.isNotEmpty(sleepCareBodyMotionResult)) {
                           userInfo.setAction(sleepCareBodyMotionResult.isOutofTimeNotAction());
                       }
                   }

                    // 写入redis缓存
                    redisTemplate.opsForValue().set(RedisKeyUtil.getSleepCareKey(userId), userInfo);
                }
            }
        } catch (Exception e) {
            log.error("sleep care proccess refresh data error ====> {}", e.getMessage());
        }
    }

    /**
     * 获取睡眠卫士全部数据
     *
     * @return the sllp care all user info result
     */
    private SleepCareAllUserInfoResult getAllUserInfo() {

        SleepCareAllUserInfoParam sleepCareAllUserInfoParam = new SleepCareAllUserInfoParam();
        sleepCareAllUserInfoParam.setCorpId(SleepCareConstant.SLEEP_CARE_CORP_ID);

        Map<String, Object> param = JSONObject.fromObject(sleepCareAllUserInfoParam);
        try {
            JSONObject result = JSONObject.fromObject(httpClientService.doGet(
                    SleepCareConstant.SLEEP_CARE_GET_CORP_ALL_USER_INFO, param));

            Integer errorCode = (Integer) result.get(SleepCareConstant.SLEEP_CARE_KEY_ERROR_CODE);
            log.info("sleep care get all user info result error code = {}", errorCode);
            if (errorCode.equals(SleepCareErrorCodeEnum.ACCESS_VIOLATION.getCode())) {
                // 非法访问，key错误 -- 需要登录
                if (SleepCareConstant.MAX_LOGIN_COUNT >= loginCount) {
                    // 判断登录次数
                    return null;
                }
                // 登录
                SleepCareLoginResult sleepCareLoginResult = login();

                if (sleepCareLoginResult.getErrorCode().equals(SleepCareErrorCodeEnum.LOGIN_SUCCESS.getCode())) {
                    // 登录成功
                    return getAllUserInfo();
                }

            } else if (errorCode.equals(SleepCareErrorCodeEnum.OBJECT_CORRECT.getCode())) {
                // 获取到数据
                Map<String, Object> map = new HashMap<>();
                map.put("allUserInfoList", SleepCareUserInfo.class);
                return (SleepCareAllUserInfoResult) JSONObject.toBean(result, SleepCareAllUserInfoResult.class, map);
            } else {
                // 其他类型错误
                String errorMsg = String.format("获取数据失败.错误码 = %s, 错误内容 = %s",
                        errorCode, SleepCareErrorCodeEnum.getMean(errorCode));
                throw new RuntimeException(errorMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 睡眠卫士登录 - 保持session
     *
     * @return the sleep care login result
     */
    public SleepCareLoginResult login() {

        SleepCareLoginResult sleepCareLoginResult = null;

        SleepCareLoginParam sleepCareLoginParam = new SleepCareLoginParam();
        sleepCareLoginParam.setName(SleepCareConstant.SLEEP_CARE_NAME);
        sleepCareLoginParam.setPassword(SleepCareConstant.SLEEP_CARE_PASSWORD);

        Map<String, Object> param = JSONObject.fromObject(sleepCareLoginParam);

        try {
            JSONObject result = JSONObject.fromObject(httpClientService.doGet(
                    SleepCareConstant.SLEEP_CARE_GET_CORP_ALL_USER_INFO, param));
            log.info("sleep care login result = {}", result.toString());
            sleepCareLoginResult = (SleepCareLoginResult) JSONObject.toBean(result, SleepCareLoginResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        loginCount++;

        return sleepCareLoginResult;
    }

    /**
     * 获取睡眠卫士历史体动数据
     *
     * @param sleepCareBodyMotionParam  sleep care body motion param
     *
     * @return  sleep care body motion result
     */
    private SleepCareBodyMotionResult getBodyMotion(SleepCareBodyMotionParam sleepCareBodyMotionParam) {
        return null;
    }

}
